package com.example.leetcode;

/**
 * 21. 合并两个有序链表
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class Leetcode0021 {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode dummyHead = new ListNode();
        ListNode curr = dummyHead;
        ListNode curr1 = list1;
        ListNode curr2 = list2;
        while(curr1 != null || curr2 != null) {

            if(curr1 == null) {
                curr.next = curr2;
                curr2 = curr2.next;
            } else if(curr2 == null) {
                curr.next = curr1;
                curr1 = curr1.next;
            } else {
                if (curr1.val <= curr2.val) {
                    curr.next = curr1;
                    curr1 = curr1.next;
                } else {
                    curr.next = curr2;
                    curr2 = curr2.next;
                }
            }
            curr = curr.next;
        }
        return dummyHead.next;
    }
}
